<?php
/**
 * 登录用户 Auth 验证中间件
 */
namespace App\Http\Middleware;

use Closure;
use Exception;

class AuthToken
{
    /**
     * Handle an incoming req.
     *
     * @param  \Illuminate\Http\Request  $req
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($req, Closure $next)
    {
        // $auth = $req->header('_v3_Auth') ?? $req->cookie('_v3_Auth');
        $auth = $req->header('Authorization') ?? ($req->input('Authorization') ?? '');
        if (!$auth) {
            throw new Exception("Not Parameter Authorization", 401);
        }
        list($pwd, $uid, $rid, $project) = explode("\t",authcode(str_replace('###','+',urldecode($auth)), 'DECODE'));
        // 判断项目
        if (strval($project) !== 'pet-service' || !$uid || !$rid) {
            throw new Exception("Please Login", 402);
        }
        $req['uid'] = $uid;
        $req['rid'] = $rid;

        return $next($req);
    }
}
